package com.leyou.user.inter.fallback;

import com.leyou.common.bean.Result;
import com.leyou.common.bean.ResultCode;
import com.leyou.user.inter.api.IUserService;
import com.leyou.user.inter.dto.UserLoginDTO;
import com.leyou.user.inter.dto.UserRegisterDTO;
import com.leyou.user.inter.pojo.User;
import com.netflix.hystrix.exception.HystrixTimeoutException;
import feign.hystrix.FallbackFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.validation.Valid;

/**
 * @author zqq
 * @ClassName UserServiceFallbackFactory
 * @Description
 * @date 2020/3/9-20:19
 */
@Component
@Slf4j
public class UserServiceFallbackFactory implements FallbackFactory<IUserService> {
    @Override
    public IUserService create(Throwable throwable) {
        return new IUserService(){
            @Override
            public Result<Boolean> checkUserData(String data, Integer type) {
                log.error("fallback,causedby: " + throwable);
                if (throwable != null) {
                    if (throwable instanceof HystrixTimeoutException) {
                        return Result.newFailure(ResultCode.S_REQUEST_TIME_OUT);
                    }
                }
                return Result.newFailure(ResultCode.S_SYSTEM_EXCEPTION);
            }

            @Override
            public Result<Boolean> sendVerifyCode(String phone) {
                log.error("fallback,causedby: " + throwable);
                if (throwable != null) {
                    if (throwable instanceof HystrixTimeoutException) {
                        return Result.newFailure(ResultCode.S_REQUEST_TIME_OUT);
                    }
                }
                return Result.newFailure(ResultCode.S_SYSTEM_EXCEPTION);
            }

            @Override
            public Result<Boolean> register(@Valid UserRegisterDTO dto) {
                log.error("fallback,causedby: " + throwable);
                if (throwable != null) {
                    if (throwable instanceof HystrixTimeoutException) {
                        return Result.newFailure(ResultCode.S_REQUEST_TIME_OUT);
                    }
                }
                return Result.newFailure(ResultCode.S_SYSTEM_EXCEPTION);
            }

            @Override
            public Result<User> queryUser(UserLoginDTO dto) {
                log.error("fallback,causedby: " + throwable);
                if (throwable != null) {
                    if (throwable instanceof HystrixTimeoutException) {
                        return Result.newFailure(ResultCode.S_REQUEST_TIME_OUT);
                    }
                }
                return Result.newFailure(ResultCode.S_SYSTEM_EXCEPTION);
            }
        };
    }
}
